from xmlrpclib import ServerProxy,Fault,ProtocolError
from Game import Game
from News import News
from Exception_ import FgsException
from User import User

class Portal(object):
    def __init__(self, uri, user, password, cache):
        self.uri = uri
        self._proxy = ServerProxy(self.uri)
        self._cache = cache

        self.user = User(self, user)
        self.user.login(password)

    def __getattr__(self, name):
        if name == 'games':
            self.__dict__['games'] = self._get_games()
            return self.__dict__['games']
        elif name == 'news':
            self.__dict__['news'] = self._get_news()
            return self.__dict__['news']
        else:
            raise AttributeError

    def clear(self):
        del self.__dict__['servers']
        del self.__dict__['news']

    def _get_games(self):
        games = []
        try:
            game_list = self._proxy.user.getgamelist()
        except Fault, f:
            raise FgsException("XmlRpc call faulted: %s" % f.faultString)
        except ProtocolError, p:
            raise FgsException("Transport error during XmlRpc call on %s: %s" % (p.errmsg, p.url))

        for game in game_list:
            games.append(Game(self, self._cache, **game))

        return dict([(x,games[x]) for x in range(len(games))])

    def _get_news(self):
        return News(self)
